/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.fw;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 */
public class WireAdapter<T>
{
	private JAXBContext context;
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;

	public WireAdapter(Class<T> clazz)
	{
		try
		{
			this.context = JAXBContext.newInstance(clazz);
			this.marshaller = this.context.createMarshaller();
			this.unmarshaller = this.context.createUnmarshaller();

			this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new java.lang.Boolean(true));
		}
		catch(java.lang.Exception e)
		{
			throw new java.lang.RuntimeException(e);
		}
	}

	public java.lang.String serialize(T object)
	{
		try
		{
			java.io.StringWriter writer = new java.io.StringWriter();
			marshaller.marshal(object, writer);
			return writer.getBuffer().toString();
		}
		catch(java.lang.Exception e)
		{
			throw new java.lang.RuntimeException(e);
		}
	}

	public T deserialize(java.lang.String string)
	{
		try
		{
			return (T) unmarshaller.unmarshal(new java.io.StringReader(string));
		}
		catch(java.lang.Exception e)
		{
			throw new java.lang.RuntimeException(e);
		}
	}
}
